<template>
<div class="form-cell">
  <van-field readonly clickable name="picker" :value="pickerValue" :label="label" :placeholder="placeholder || '请选择'"
    @click="showBlank" :rules="rules" :required="required === undefined ? false : true"/>
  <van-popup v-model="showPicker" position="bottom">
    <van-picker show-toolbar :columns="columns" @confirm="onConfirm" @cancel="showPicker = false"/>
  </van-popup>
</div>
</template>

<script>
export default {
  props: [ 'label', 'value', 'placeholder', 'option', 'readonly', "required", "rules" ],
  data() {
    return {
      pickerValue: '',
      showPicker: false,
    } 
  },
  watch: {
    value() {
      if (this.value || this.value === 0) {
        let item = this.option.find(item => item.value === this.value);
        if (item) {
          this.pickerValue = item.label;
          return ;
        }
      }
      this.pickerValue = '';
    },
    option() {
      if (this.value || this.value === 0) {
        let item = this.option.find(item => item.value === this.value);
        if (item) {
          this.pickerValue = item.label;
          return ;
        }
      }
      this.pickerValue = '';
    }
  },
  computed: {
    columns() {
      return this.option.map(item => item.label);
    }
  },
  methods: {
    onConfirm(label, index) {
      if (this.option[index].value === this.value) {
        this.showPicker = false;
        return ;
      }
      this.pickerValue = label;
      this.$emit('input', this.option[index].value);
      this.$emit('change', this.option[index].value);
      this.showPicker = false;
    },
    showBlank() {
      if (this.readonly) return ;
      this.showPicker = true;
    }
  },
  mounted() {
    if (this.value || this.value === 0) {
      let item = this.option.find(item => item.value === this.value);
      if (item) {
        this.pickerValue = item.label;
      }
    }
  }
}
</script>
